import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import {useParams} from "react-router";
import "./css/EditMenu.less";
import {getFormView} from "../../services/ViewService.tsx";
import EditMenuItem from "./EditMenuItem.tsx";
import {loadMenu} from "../../services/MenuService.tsx";

interface EditMenuProps {
    editView: string
}

const EditMenu: FC<EditMenuProps> = (props) => {
    const {id} = useParams();
    const [view, setView] = useState<any[]>([]),
        [menuInfo, setMenuInfo] = useState(null);

    const loadView: Function = useCallback(async () => {
        const {editView}: { editView: string } = props;
        const result: any = await getFormView(editView);
        setView(result.form);
    }, [props]);

    const loadMenuInfo = useCallback(async () => {
        const res = await loadMenu({id: id});
        setMenuInfo(res)
    }, [id]);

    const init = useCallback(async () => {
        await loadView();
        await loadMenuInfo()
    }, [id])

    useEffect(() => {
        init()
    }, [id]);


    const renderEdit = useMemo(() => {
        if (!menuInfo || !view) {
            return
        }
        return (
            <div className="sf_core_menu_edit_content">
                <div className="sf_core_menu_edit_content_item"
                     style={{top: 20, left: "50%", transform: "translateX(-50%)"}}>
                    <EditMenuItem
                        key={menuInfo.id}
                        view={view}
                        initValues={menuInfo}/>
                </div>
            </div>
        )
    }, [view, menuInfo]);

    const renderEditMenu = useMemo(() => {
        return (
            <div className="sf_core_menu_edit">
                {renderEdit}
            </div>
        )
    }, [view, menuInfo]);

    return (renderEditMenu);
};

export default React.memo(EditMenu);

